﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.Model;
using MyBlog.Model.DTO;


namespace MyBlog.WebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class WriterInfoController : ControllerBase
    {
        private readonly IWriterInfoService writerInfoService;

        public WriterInfoController(IWriterInfoService writerInfoService)
        {
            this.writerInfoService = writerInfoService;
        }

        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name,string userName,string userpwd)
        {
            //数据验证

            WriterInfo writerInfo = new()
            {
                Name = name,
                UserName = userName,
                UserPwd = MD5Helper.MD5Encrypt32(userpwd)
            };
            var oldWriter =await  writerInfoService.FindAsync(c => c.UserName == userName);
            if (oldWriter != null) return ApiResultHelper.Error("账号已经存在");
            if (!await writerInfoService.CreateAsync(writerInfo))
                return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success(writerInfo);
        }
        [HttpPut("Edit")]
        public async Task<ApiResult> Edit(string name)
        {
            var id = Convert.ToInt32(this.User.FindFirst("Id").Value);
            var writer = await writerInfoService.FindAsync(id);
            writer.Name = name;
            bool b = await writerInfoService.EditAsync(writer);
            if (!b) return ApiResultHelper.Error("修改失败");
            return ApiResultHelper.Success("修改成功");
        }
        [HttpDelete("Delete")]
        public async Task<ApiResult> Delete(int id)
        {
            if (!await writerInfoService.DeleteAsync(id))
                return ApiResultHelper.Error("删除失败");
            return ApiResultHelper.Success(true);
        }
        [AllowAnonymous]//匿名访问
        [HttpGet("FindWriter")]
        public async Task<ApiResult> FindWriter([FromServices]IMapper mapper, int id)
        {
            var writer = await writerInfoService.FindAsync(id);
            //类型映射 
            return ApiResultHelper.Success(mapper.Map<WriterDTO>(writer));
        }
    }
}
